<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ContentWrap } from '@/components/ContentWrap'
import { getConfigDetail, addConfig, editConfig } from '@/api/config/admin'
import { ElMessage, ElForm } from 'element-plus'

const route = useRoute()
const router = useRouter()

// 表单数据
const form = reactive({
  id: 0,
  key: '',
  value: '',
  description: ''
})

// 表单验证规则
const rules = {
  key: [{ required: true, message: '请输入键名', trigger: 'blur' }],
  value: [{ required: true, message: '请输入值', trigger: 'blur' }]
}

const formRef = ref<InstanceType<typeof ElForm>>()
const loading = ref(false)
const isEdit = ref(false)

// 获取配置详情
const fetchConfigDetail = async (id: number) => {
  try {
    loading.value = true
    const res = await getConfigDetail(id)
    if (res.code === 200) {
      const configData = res.data
      form.id = configData.id
      form.key = configData.key
      form.value = configData.value
      form.description = configData.description
    } else {
      ElMessage.error(res.message || '获取配置详情失败')
    }
  } catch (error) {
    ElMessage.error('获取配置详情失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = () => {
  if (!formRef.value) return

  formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        let res
        if (isEdit.value) {
          // 编辑模式
          res = await editConfig(form.id, form)
          if (res.code === 200) {
            ElMessage.success('更新成功')
          } else {
            ElMessage.error(res.message || '更新失败')
          }
        } else {
          // 新增模式
          res = await addConfig(form)
          if (res.code === 200) {
            ElMessage.success('创建成功')
          } else {
            ElMessage.error(res.message || '创建失败')
          }
        }

        if (res.code === 200) {
          // 跳转到配置列表页面并携带刷新参数
          router.push({
            name: 'ConfigIndex',
            query: { refresh: '1' }
          })
        }
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 返回配置列表
const goBack = () => {
  router.push({ name: 'ConfigIndex' });
}

onMounted(() => {
  const id = route.params.id as string
  if (id && id !== '0') {
    isEdit.value = true
    fetchConfigDetail(Number(id))
  } else {
    isEdit.value = false
  }
})
</script>

<template>
  <ContentWrap
    :title="isEdit ? '编辑配置' : '新增配置'"
    :message="isEdit ? '编辑配置信息' : '添加新的配置信息'"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      style="max-width: 600px"
      :disabled="loading"
    >
      <el-form-item label="键名" prop="key">
        <el-input v-model="form.key" placeholder="请输入键名" :disabled="isEdit" />
      </el-form-item>

      <el-form-item label="值" prop="value">
        <el-input v-model="form.value" type="textarea" placeholder="请输入值" :rows="4" />
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input v-model="form.description" type="textarea" placeholder="请输入描述" :rows="3" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm" :loading="loading">
          {{ isEdit ? '更新' : '提交' }}
        </el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>

<style scoped>
:deep(.el-form-item__content) {
  justify-content: flex-start;
}
</style>
